<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\model\AccessModel;
use app\admin\model\RoleAccessModel;
class Access extends Base
{
	/**
	 * 权限列表
	 */
    public function index(){
    	return $this->fetch();
    }

    /**
     * 权限添加
     */
    public function add(){
    	$info['actions']="添加";
    	$info['pid']=request()->get('pid',0,'intval');
        if(request()->isPost()){
            $data=request()->post();
            try {
                $this->validate($data,'Access');
            } catch (\Exception $e) {
                return $this->error($e->getMessage());
            }
            $data['is_show']=(isset($data['is_show']) && $data['is_show']=="on")?1:0;
            $data['is_blank']=(isset($data['is_blank']) && $data['is_blank']=="on")?1:0;
            if(AccessModel::create($data)){
                return $this->success('添加成功',(string)url('index'));
            }
            return $this->error('添加失败');
        }
        $AccessSelect=AccessModel::getAccessSelect();
        $this->assign(['info'=>$info,'AccessSelect'=>$AccessSelect]);
    	return $this->fetch();
    }
    /**
     * 权限修改
     */
    public function edit(){
    	$id=request()->get('id','','intval');
        if(!empty($id)){
            $info=AccessModel::find($id);
            if(empty($info)){
                return $this->error('信息不存在');
            }
            $info=$info->toArray();
            $info['actions']='修改';
        }else{
            return $this->error('信息不存在');
        }

        if(request()->isPost()){
            $data=request()->post();
            try {
                $this->validate($data,'Access');
            } catch (\Exception $e) {
                return $this->error($e->getMessage());
            }
            $data['is_show']=(isset($data['is_show']) && $data['is_show']=="on")?1:0;
            $data['is_blank']=(isset($data['is_blank']) && $data['is_blank']=="on")?1:0;
            if(AccessModel::update($data,['id'=>$id])){
                return $this->success('修改成功',(string)url('index'));
            }
            return $this->error('修改失败');
        }
        $AccessSelect=AccessModel::getAccessSelect();
        $this->assign(['info'=>$info,'AccessSelect'=>$AccessSelect]);
    	return $this->fetch('add');
    }
    /**
     * 权限删除
     */
    public function del(){
    	$id=request()->post('id/d');
        if(!empty(AccessModel::where(['pid'=>$id])->find())){
            return $this->error('请先删除子级');
        }

        if(AccessModel::destroy($id) && RoleAccessModel::where(['access_id'=>$id])->delete()){
            return $this->success('删除成功');
        }
	    return $this->error('删除失败,请联系网站管理员');
    }
    /**
     * 获取下拉权限列表
     */
    public function getAccess(){
    	$Access=AccessModel::getAccess();
    	return $this->showList($Access,count($Access));
    }

}
